#===============================================================================
# Test break timer
#===============================================================================
##
##
##import os, sys, pylab, random
import wx
#import numpy as np
#from plotpanel import PlotPanel
#from matplotlib.patches import Rectangle
#import database
#from datetime import date, time, datetime, timedelta
#from controls import MenuPanel, ControlPanel
#from config import ConfigData
#from myopace_serial import Console
import threading
import time

  
#===============================================================================
#    CLASS: BreakDialog
#    Creates a frame for the break timer
#===============================================================================
class BreakDialog(wx.Frame):
    """ This class implements a basic timer with an elapsed time display.
        The constructor takes a minimum of two arguments:
            - a callable object to be run when the timer reaches the specified time
            - the length of time before running callable object (seconds)
        The timer is run in a separate thread as it simply sits and waits 1 sec
        between each timer/display update. The implementation uses a threading.Event
        object. The object can be set to break the while loop and end the break. This
        is done when the button is clicked, and also when the window is closed. So
        every case leads to the execution of the _end_timer() function, which
        closes the window.
    """
    def __init__(self, on_timer, break_length, parent=None, id=-1):
        wx.Frame.__init__(self, parent, id, title='Take a break :-)', size=(300, 150))
        self.ctrl = parent
        self.on_timer = on_timer
        self._break_len = break_length
        self.break_time = 0
        
        panel = wx.Panel(self, -1)
        self.break_button = wx.Button(panel, -1, 'Continue trials', size=(200, 30))
        self.Bind(wx.EVT_BUTTON, self._on_button, self.break_button)

        time_size = (200, 30)
        self.time_display = wx.TextCtrl(panel, -1,
                                         'Mins: 0    Secs: 0',
                                         size=time_size,
                                         name="time")
        self.time_display.SetEditable(False)
        
        text = 'Break length: %i seconds' % self._break_len
        self.break_text = wx.StaticText(panel, -1, text)
        
        box = wx.StaticBox(panel, -1, "Break Timer")
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        sizer.Add(self.time_display, flag=wx.ALIGN_CENTER)
        sizer.Add(self.break_text, flag=wx.ALIGN_CENTER)
        sizer.Add(self.break_button, flag=wx.ALIGN_CENTER)
        panel.SetSizer(sizer)

        self.Bind(wx.EVT_CLOSE, self._on_close)
        self.Centre()
        self.Show()

    def start(self):
        start_time = time.time()
        duration = 0
        while 1:
            counter = time.time() - start_time
            if int(counter) > duration:
                self._update_time()
                duration = counter
            # End break if the time is up
            if self.break_time >= self._break_len:
                break
        self._end_timer(None)
        
    def _update_time(self):
        # get break_time time from computer
        self.break_time += 1
        mins = 0
        if self.break_time >= 60:
            mins = self.break_time / 60
        time_str = 'Mins: %s    Secs: %s' % (mins, self.break_time)
        print time_str
        self.time_display.SetValue(time_str)
        self.Refresh()

    def _on_button(self, event):
        # Clicking the button overrides the timer and ends the break
        self._end_timer()

    def _end_timer(self, event):
        self.on_timer()
        self.Destroy()
        
    def _on_close(self, event):
        # Run when the break dialog is closed manually
#        self.ctrl.but_ctrl.pause_button.Enable()
        self.Destroy()
        event.Skip()
        
        
        
class MyApp(wx.PySimpleApp):
    def __init__(self):
        wx.PySimpleApp.__init__(self)
        print 'my app started'
        frame = wx.Frame(None, -1, 'Main frame')
        panel = wx.Panel(frame, -1)
        bgcolour = '#aaaaaa'
        panel.SetBackgroundColour(bgcolour)
        
        image0 = wx.Image("D:\\button_images\\button_0.jpg", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        image1 = wx.Image("D:\\button_images\\button_1.jpg", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        
        start_button = wx.BitmapButton(panel, -1, bitmap=image0, style=wx.BU_EXACTFIT)
        start_button.SetBitmapHover(image1)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(start_button, 0, wx.ALIGN_CENTER)
        panel.SetSizer(sizer)
        frame.Show()
        
        print wx.__version__
        
    def _start_break(self, event):
        self.break_frame = BreakDialog(self.on_break_end, 5)
        self.break_frame.start()

    def on_break_end(self):
        print 'break finished'
        
    def on_close(self):
        print 'on close'

def main():
    app = MyApp()
    app.MainLoop()

if __name__ == '__main__':
    main()
